package com.websocket.controller;

import com.alibaba.fastjson.JSON;
import com.websocket.config.DomainName;
import com.websocket.config.UrlConfig;
import com.websocket.constant.RedisConstant;
import com.websocket.dto.DialogueList;
import com.websocket.dto.WechatDTO;
import com.websocket.entity.UserInfo;
import com.websocket.entity.User_;
import com.websocket.enums.FlagEnum;
import com.websocket.repository.UserInfoRepository;
import com.websocket.repository.mongo.DialogueListRepository;
import com.websocket.service.Impl.UserServiceImpl;
import com.websocket.service.OtoWechatService;
import com.websocket.util.FileSaveLocalUtil;
import com.websocket.util.KeyUtil;
import com.websocket.vo.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/index")
@Slf4j
public class IndexController {
    @Autowired
    private OtoWechatService otoWechatService;
    @Autowired
    private DomainName domainName;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private DialogueListRepository dialogueListRepository;

    @GetMapping("/first")
    public ModelAndView first(){
        return new ModelAndView("page/demo");
    }
    @GetMapping("/chat")
    public ModelAndView chat(@RequestParam("toUserid") String toUserid,
                             @RequestParam("userId") String userid,
                             Map<String,Object> map)
    {
        UserInfo toUserInfo = userInfoRepository.findByUserId(Integer.valueOf(toUserid));
        UserInfo userInfo = userInfoRepository.findByUserId(Integer.valueOf(userid));
        //@RequestParam("token") String token
        map.put("domainName",domainName.getName());
        map.put("server_ip", UrlConfig.SERVER_IP);
        map.put("server_port", UrlConfig.PORT);
        map.put("toUserid",toUserid);
        map.put("toUserImg",toUserInfo.getImgUrl());
        map.put("userImg",userInfo.getImgUrl());
        map.put("userId",userid);
        if("/wlzz/images/logo.jpg".equals(userInfo.getImgUrl())){
            map.put("userImg","http://39.108.97.134:8886/wlzz/images/logo.jpg");
        }
        if("/wlzz/images/logo.jpg".equals(toUserInfo.getImgUrl())){
            map.put("toUserImg","http://39.108.97.134:8886/wlzz/images/logo.jpg");
        }
        return new ModelAndView("page/chat",map);
    }
    @GetMapping("/search")
    public ModelAndView search(Map<String,Object> map)
    {
        map.put("domainName",domainName.getName());
        return new ModelAndView("page/search");
    }
    @GetMapping("/dialogue")
    public ModelAndView friendList(Map<String,Object> map)
    {
        map.put("domainName",domainName.getName());
        map.put("server_ip", UrlConfig.SERVER_IP);
        map.put("server_port", UrlConfig.PORT);
        return new ModelAndView("page/dialogue",map);
    }
    @GetMapping("/person")
    public ModelAndView person(@RequestParam("toUserid") String toUserid,Map<String,Object> map)
    {
        UserInfo userInfo = userInfoRepository.findByUserId(Integer.valueOf(toUserid));
        map.put("domainName",domainName.getName());
        map.put("nickName",userInfo.getNickName());
        map.put("imgUrl",userInfo.getImgUrl());
        map.put("toUserid",userInfo.getUserId());
        map.put("schoolName",userInfo.getSchoolName());
        map.put("motto",userInfo.getMotto());
        map.put("sex",userInfo.getSex());
        if("/wlzz/images/logo.jpg".equals(userInfo.getImgUrl())){
            map.put("imgUrl","http://39.108.97.134:8886/wlzz/images/logo.jpg");
        }
        return new ModelAndView("page/person",map);
    }
    @GetMapping("/contacts")
    public ModelAndView contacts(Map<String,Object> map)
    {
        map.put("domainName",domainName.getName());
        return new ModelAndView("page/contacts",map);
    }


    @PostMapping("/reloadChat")
    public String contacts(@RequestParam("token") String token,
                           @RequestParam("toUserid") String toUserid,
                           @RequestParam("page") Integer page,
                           @RequestParam("size") Integer size)
    {
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.LOGIN_SUCCESS_TOKEN, token));
        if(tokenValue==null){
                return "No login";
        }
        User_ user = userService.findByPhone(tokenValue);
        PageRequest request = PageRequest.of(page,size,new Sort(Sort.Direction.DESC,"create_time"));
        PageVO<WechatDTO> pageVO = otoWechatService.findByUseridAndToUserid(user.getUserId().toString(),toUserid,toUserid,user.getUserId().toString(),request);
        String json = JSON.toJSONString(pageVO);
        return json;
    }
    @PostMapping("/userGetMsg")  //已接受消息
    public WechatDTO userGetMsg(@RequestParam("_id") String _id){
        return otoWechatService.userGetMsg(_id);
    }
    @PostMapping("/deleteDialog")
    public String deleteDialog(@RequestParam("token") String token,
                               @RequestParam("userid2") String userid2){
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.LOGIN_SUCCESS_TOKEN, token));
        if(tokenValue==null){
            return "No login";
        }
        User_ user = userService.findByPhone(tokenValue);
        DialogueList dialogueList =
                dialogueListRepository.findByUserid1AndUserid2AndFlag(user.getUserId(),Integer.valueOf(userid2), FlagEnum.NO_DELETE.getCode());
        if(dialogueList==null){
            return "已删除";
        }else{
            dialogueList.setFlag(FlagEnum.DELETE.getCode());
            dialogueListRepository.save(dialogueList);
            return "success";
        }
    }
    @GetMapping("/test")
    public ModelAndView test()
    {
        return new ModelAndView("page/test");
    }

    @PostMapping("/uploadImg")
    @CrossOrigin
    public String uploadImg(@RequestParam("_") String _, HttpServletRequest request) {
        try {
            List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file");

            System.out.println(files.get(0).getSize());
            String path = FileSaveLocalUtil.getYearAndMonth();   //得到路径
            String fileName = KeyUtil.genUniqueKey();
            FileSaveLocalUtil.savePic(files.get(0).getInputStream(),path,fileName);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://39.108.97.134:8886/wlzz");
            stringBuilder.append("/wlzzUser/getImg?");
            stringBuilder.append("flag=");
            String parameter = path+fileName;
            stringBuilder.append(URLEncoder.encode(parameter, "utf-8"));
            return stringBuilder.toString();
        }catch (Exception e){
            e.printStackTrace();
            return "fail";
        }
    }
}

